#include "comm.hpp"


//一旦有人把数据写入到共享内存，其实我们立马能看到了
//不需要经过系统调用，直接就能看到数据了


int main()
{
    Init init;
    
    // 创建共享内存
    int shmid = CreatShm();
    // log(Debug,"creat shm done");
    // sleep(5);

    // 挂接共享内存
    char *shmaddr = (char *)shmat(shmid, nullptr, 0);
    // log(Debug,"attach shm done,shmaddr: 0x%x",shmaddr);
    // sleep(5);

    // 打开信道
    int fd = open(FIFO_FILE, O_RDONLY); // 等待写入方打开之后，自己才会打开文件，向后执行， open 阻塞了！
    //std::cout<<fd<<std::endl;
    if (fd < 0)
    {
        log(Fatal, "error string: %s  error code: %d", strerror(errno), errno);
        exit(FIFO_OPEN_ERR);
    }

    struct shmid_ds shmds;
    while (true)
    {

        char c;
        ssize_t s = read(fd, &c, 1);
        if (s == 0)
            break;
        else if (s < 0)
            break;

        std::cout << "cylinder say@" << shmaddr << std::endl;
        sleep(1);

        shmctl(shmid, IPC_STAT, &shmds);
        std::cout << "shm size: " << shmds.shm_segsz << std::endl;
        std::cout << "shm nattch: " << shmds.shm_nattch << std::endl;
        printf("shm key: 0x%x\n", shmds.shm_perm.__key);
        std::cout << "shm mode: " << shmds.shm_perm.mode << std::endl;
    }

    // 去关联
    shmdt(shmaddr);
    // log(Debug,"detach shm done,shmaddr: 0x%x",shmaddr);
    // sleep(5);

    // 释放共享内存
    shmctl(shmid, IPC_RMID, nullptr);
    // log(Debug,"destroy shm done,shmaddr: 0x%x",shmaddr);
    // sleep(5);

    close(fd);

    return 0;
}
